import paho.mqtt.client as mqtt
import re

HOST = "douzi.wiki"
PORT = 1883
humidity = 60
temperature = 26
illuminance = 120
curtainVeil_State = 1;

def on_message_callback(client, userdata, message):
    global humidity
    global temperature
    global illuminance
    global curtainVeil_State

    # 回报数据格式化
    print(message.topic + " " + ":" + str(message.payload))
    data = re.findall("b'(.+?)'", str(message.payload))
    print(data)

    # 自动判断光照度数据
    if illuminance >= 900:
        print("光照度大于900lux,关闭窗帘。")
        if curtainVeil_State == 1:
            client.publish("/intelligentCurtain/curtainVeil", "off", 0)
            curtainVeil_State = 0

    # 储存光照数据
    if message.topic == "/intelligentCurtain/illuminance":
        illuminance = float(data[0])
        print(illuminance)

    # 储存温湿度数据
    if message.topic == "/intelligentCurtain/humiture":
        humiture_data = data[0].split("#", 2)
        humidity = float(humiture_data[1])
        temperature = float(humiture_data[2])


def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))
    client.subscribe("/intelligentCurtain/illuminance")


def main():
    client = mqtt.Client('test')
    client.connect(HOST, PORT, 60)
    client.on_connect = on_connect
    client.publish("/intelligentCurtain/serverStatus", "计算模块上线", 1)
    client.on_message = on_message_callback
    client.loop_forever()


if __name__ == '__main__':
    print('服务器上线')
    main()
